<?php defined('SYSPATH') or die('Access error!');
/**
 *日志类
 */
class Log {

	public static $timestamp = 'Y-m-d H:i:s';

	public static $timezone;

	public static $write_on_add = FALSE;

	private static $_instance;

	public static function instance()
	{
		if (self::$_instance === NULL)
		{
			self::$_instance = new self;

			register_shutdown_function(array(self::$_instance, 'write'));
		}

		return self::$_instance;
	}

	private $_messages = array();

	private $_writers = array();

	public function attach(Log_Writer $writer, array $types = NULL)
	{
		$this->_writers["{$writer}"] = array
		(
			'object' => $writer,
			'types' => $types
		);

		return $this;
	}

	public function detach(Log_Writer $writer)
	{
		unset($this->_writers["{$writer}"]);

		return $this;
	}

	/**
	 * 增加一个日志
	 *
	 *     $log->add('error', 'Could not locate user: :user', array(
	 *         ':user' => $username,
	 *     ));
	 *
	 * @param   string  type of message
	 * @param   string  message body
	 * @param   array   values to replace in the message
	 */
	public function add($type, $message, array $values = NULL)
	{
		if ($values)
		{
			$message = strtr($message, $values);
		}

		$this->_messages[] = array
		(
			'time' => Date::floortime(''),
			'type' => $type,
			'body' => $message,
		);

		if (self::$write_on_add)
		{
			$this->write();
		}

		return $this;
	}

	/**
	 * 写入或者删除日志
	 */
	public function write()
	{
		if (empty($this->_messages))
		{
			return;
		}

		$messages = $this->_messages;

		$this->_messages = array();

		foreach ($this->_writers as $writer)
		{
			if (empty($writer['types']))
			{
				$writer['object']->write($messages);
			}
			else
			{
				$filtered = array();

				foreach ($messages as $message)
				{
					if (in_array($message['type'], $writer['types']))
					{
						$filtered[] = $message;
					}
				}

				$writer['object']->write($filtered);
			}
		}
	}

}
